import json
from datetime import datetime

from common.json_util import to_dicts, to_dict
from common.oss_upload import get_file_url
from daos.album_episode_info_dao import *

from daos.image_library_dao import query_image_library
from daos.video_library_dao import query_video_library
from models.biz_enum import SystemLogModule
from rules import db_commit, PAGINATION_PAGE_SIZE
from rules.system_log_rule import create_system_log


def search_album_episode_info(pk):
    result = query_album_episode_info(pk)
    return result.to_dict()


def search_album_episode_info_by_album_id(album_id, pk):
    album_episode_orm = query_album_episode_info_by_album_id(album_id, pk)
    album_episode_dict = to_dict(album_episode_orm)

    covers = []
    for covers_dict in album_episode_dict.get('covers'):
        file_url = get_file_url(covers_dict.get('file_name'), expires=600)
        cover = {
            "id": covers_dict.get('image_library_id'),
            "title": covers_dict.get('title'),
            "file_url": file_url
        }
        covers.append(cover)
    album_episode_dict['covers'] = json.dumps(covers)

    video_file_url = get_file_url(album_episode_dict.get('video_library').get('file_name'), expires=600)
    video_library = {
        "id": album_episode_dict.get('video_library').get('video_library_id'),
        "title": album_episode_dict.get('video_library').get('title'),
        "file_url": video_file_url
    }
    album_episode_dict['video_library'] = json.dumps(video_library)

    return album_episode_dict


def search_album_episode_info_with_page(page_index, data_param):
    data_param['page'] = page_index
    data_param['page_size'] = PAGINATION_PAGE_SIZE
    result = query_album_episode_info_with_page(data_param)
    item_dicts = to_dicts(result.items)
    result.items = item_dicts
    return result


def create_album_episode_info(form, current_user):
    is_commit = False
    album_id = int(form.album_id.data)
    seq_index = int(form.seq_index.data)
    data_param = dict(album_info_id=album_id, seq_index=seq_index)
    album_episode_info_count = query_album_episode_info_count(data_param)
    if album_episode_info_count > 0:
        raise Exception('已存在该集数记录')

    album_episode_info_orm = AlbumEpisodeInfo()

    album_episode_info_orm.album_info_id = album_id
    album_episode_info_orm.title = form.title.data
    album_episode_info_orm.seq_index = seq_index

    album_episode_info_orm.dy_episode_id = 0

    video_library_json = json.loads(form.video_library.data)
    video_library_orm = query_video_library(video_library_json.get('id'))
    if not video_library_orm:
        raise Exception('无效视频')

    video = {
        "video_library_id": video_library_orm.id,
        "title": video_library_orm.title,
        "file_name": video_library_orm.file_name,
        "temp_file_name": video_library_orm.temp_file_name,
        "dy_open_video_id": video_library_orm.dy_open_video_id
    }
    album_episode_info_orm.video_library = video

    # 新增封面
    covers = []
    album_covers_json = json.loads(form.covers.data)
    for item in album_covers_json:
        image_library_orm = query_image_library(item.get('id'))
        if image_library_orm:
            cover = {
                "image_library_id": image_library_orm.id,
                "title": image_library_orm.title,
                "file_name": image_library_orm.file_name,
                "dy_open_pic_id": image_library_orm.dy_open_pic_id
            }
            covers.append(cover)
    album_episode_info_orm.covers = covers

    album_episode_info_orm = add_album_episode_info(album_episode_info_orm, is_commit)
    album_episode_info_dict = album_episode_info_orm.to_dict()
    # 添加系统日志
    operation_detail_dict = dict(before_operation=None, after_operation=album_episode_info_dict)
    log_dict = dict(module=SystemLogModule.CREATE_ALBUM_EPISODE_INFO.value, operation_detail=operation_detail_dict,
                    operator=current_user.id)
    create_system_log(log_dict, is_commit)

    if not is_commit:
        db_commit()

    return album_episode_info_dict


def describe_album_episode_info(pk, form, current_user):
    is_commit = False
    now = datetime.now()
    album_id = int(form.album_id.data)
    seq_index = int(form.seq_index.data)

    if pk != int(form.album_episode_id.data):
        raise Exception('无效参数')

    album_episode_orm = query_album_episode_info_by_album_id(album_id, pk)
    if not album_episode_orm:
        raise Exception('剧集不存在')

    before_operation = album_episode_orm.to_dict().copy()

    need_update_list = ["last_update_time"]
    if form.title.data != album_episode_orm.title:
        album_episode_orm.title = form.title.data
        need_update_list.append("title")

    if seq_index != album_episode_orm.seq_index:
        data_param = dict(album_info_id=album_id, seq_index=seq_index)
        album_episode_info_count = query_album_episode_info_count(data_param)
        if album_episode_info_count > 0:
            raise Exception('已存在该集数记录')

        album_episode_orm.seq_index = seq_index
        need_update_list.append("seq_index")

    video_library_json = json.loads(form.video_library.data)
    if video_library_json.get('id') != album_episode_orm.video_library.get('video_library_id'):
        video_library_orm = query_video_library(video_library_json.get('id'))
        if not video_library_orm:
            raise Exception('视频不存在')

        video = {
            "video_library_id": video_library_orm.id,
            "title": video_library_orm.title,
            "file_name": video_library_orm.file_name,
            "temp_file_name": video_library_orm.temp_file_name,
            "dy_open_video_id": video_library_orm.dy_open_video_id
        }
        album_episode_orm.video_library = video
        need_update_list.append("video_library")

    # 更新封面图
    album_covers_json = json.loads(form.covers.data)
    form_cover_id_s = [item.get('id') for item in album_covers_json]
    orm_cover_id_s = [item.get('image_library_id') for item in album_episode_orm.covers]
    if form_cover_id_s != orm_cover_id_s:
        covers = []
        for item in album_covers_json:
            image_library_orm = query_image_library(item.get('id'))
            if image_library_orm:
                cover = {
                    "image_library_id": image_library_orm.id,
                    "title": image_library_orm.title,
                    "file_name": image_library_orm.file_name,
                    "dy_open_pic_id": image_library_orm.dy_open_pic_id
                }
                covers.append(cover)
        album_episode_orm.covers = covers
        need_update_list.append("covers")

    album_episode_orm.last_update_time = now
    update_album_episode_info(album_episode_orm, *need_update_list, is_commit=is_commit)

    # 添加系统日志
    operation_detail_dict = dict(before_operation=before_operation, after_operation=album_episode_orm.to_dict())
    log_dict = dict(module=SystemLogModule.UPDATE_ALBUM_EPISODE_INFO, operation_detail=operation_detail_dict,
                    operator=current_user.id)
    create_system_log(log_dict, is_commit)

    if not is_commit:
        db_commit()

    return
